/**
 * Created by liubin on 2015/09/18.
 */
'use strict';

import Promise from 'bluebird';
import { Response, SuperagentPromiseError } from 'superagent';
import { SUCCESS, FAIL, ERROR} from 'actions/baseAction';
import vex from 'vex';
//import history from 'common/history';
//import { FAIL } from 'actions/baseAction';
//import { AUTH } from 'actions/authAction';

const bluebirdPromiseMiddleware = store=> next=> action => {
    if (action.payload && action.payload.promise && action.payload.promise instanceof Promise) {
        const { dispatch, getState} = store;
        const promise = action.payload.promise;
        return promise.then(res => {
                //action.payload.resolve(res, dispatch, getState);
                // 判断是Response
                if (res instanceof Response) {
                    if ('status' in res.body) {
                        // 判断是正常的json通讯
                        if (res.body.status === SUCCESS) {
                            if (action.payload.resolve) {
                                action.payload.resolve(res, dispatch, getState);
                            }
                        } else {
                            if (action.payload.reject) {
                                action.payload.reject(res, dispatch, getState);
                            } else {
                                const message = res.body.message || res.body.data || '服务器错误';
                                vex.dialog.alert(message);
                            }
                        }
                    } else {
                        vex.dialog.alert('API指定错误!');
                    }
                } else {
                    if (action.payload.resolve) {
                        action.payload.resolve(res, dispatch, getState);
                    }
                }
            }, error => {
                if (error instanceof SuperagentPromiseError) {
                    if ('status' in error.body) {
                        if (action.payload.reject) {
                            action.payload.reject(error, dispatch, getState);
                        } else {
                            const message = error.body.message || error.body.data || '服务器错误';
                            vex.dialog.alert(message);
                        }
                    } else {
                        const message = error.body || '服务器错误';
                        vex.dialog.alert(message);
                    }
                } else {
                    if (action.payload.reject) {
                        action.payload.reject(error, dispatch, getState);
                    }
                }
            })
            .catch(e => {
                console.log(e);
                vex.dialog.alert('系统错误!');
            });
    } else {
        return next(action);
    }
};
export default bluebirdPromiseMiddleware;